﻿using CPPEI.BD.VMTool.Datas;
using CPPEI.BD.VMTool.Until;
using CPPEI.BD.VMTool.Untils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CPPEI.BD.VMTool.Views
{
    /// <summary>
    /// VideoMatrixCurrentWindow.xaml 的交互逻辑
    /// </summary>
    public partial class VideoMatrixCurrentWindow : Window
    {
        private Datas.Solution _solution;
        private Datas.Item _checkedMatrixItem;

        private static List<Item> _listVideoSource;
        /// <summary>
        /// 拖动的区域
        /// </summary>
        private FrameworkElement _dragScope;
        /// <summary>
        /// 用于显示鼠标跟随效果的装饰器
        /// </summary>
        private DragAdorner _adorner;
        /// <summary>
        /// 用于呈现DragAdorner的图画
        /// </summary>
        private AdornerLayer _layer;

        private Visual _dragScopeasVisual;

        private static int i;

        public VideoMatrixCurrentWindow()
        {
            InitializeComponent();
            LoadVideoMatrix();
            LoadVideoSource();
        }

        public VideoMatrixCurrentWindow(Datas.Solution solution)
        {
            InitializeComponent();
            _solution = solution;
            i = _solution.Mapping.Count;
            this.DataContext = solution;
            LoadVideoSource();
            LoadVideoMatrix();

        }


        /// <summary>
        /// 加载视频矩阵
        /// </summary>
        private void LoadVideoMatrix()
        {
            List<VideoMatrixItem> ListVideoMatrix = VMSolutionUntil.GetListVideoMatrixSource(VMSolutionUntil.GetVideoMatrixFilePath(), "VideoMatrix");
            if (ListVideoMatrix != null)
            {
                _ctlWrapPanelMatrix.Children.Clear();
                foreach (VideoMatrixItem item in ListVideoMatrix)
                {
                    Canvas matrixCanvas = new Canvas();
                    matrixCanvas.AllowDrop = true;
                    matrixCanvas.Drop += matrixCanvas_Drop;
                    matrixCanvas.DragOver += matrixCanvas_DragOver;

                    matrixCanvas.Height = 100;
                    matrixCanvas.Width = 90;
                    matrixCanvas.Margin = new Thickness(2);
                    Rectangle matrixRectangle = new Rectangle();
                    matrixRectangle.Width = 90;
                    matrixRectangle.Height = 100;
                    matrixRectangle.Fill = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF0A3E69"));

                    matrixCanvas.Children.Add(matrixRectangle);
                    Label videoLabel = new Label();
                    videoLabel.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center;
                    videoLabel.VerticalContentAlignment = System.Windows.VerticalAlignment.Bottom;
                    videoLabel.Width = 90;
                    videoLabel.Height = 100;
                    videoLabel.Content = item.Caption;
                    matrixCanvas.DataContext = item;
                    matrixCanvas.Children.Add(videoLabel);
                    matrixCanvas.Loaded += matrixCanvas_Loaded;


                    _ctlWrapPanelMatrix.Children.Add(matrixCanvas);
                }
            }
            else
            {
                _ctlWrapPanelMatrix.Children.Clear();
            }
        }

        void matrixCanvas_Loaded(object sender, RoutedEventArgs e)
        {
            if (_solution != null && _solution.Mapping != null)
            {
                if (_ctlWrapPanelVideo.Children != null)
                {
                    foreach (Canvas canvas in _ctlWrapPanelVideo.Children)
                    {
                        if (canvas != null && canvas.DataContext != null)
                        {
                            Item videoItem = canvas.DataContext as Item;

                            Canvas matrixCanvas = sender as Canvas;
                            if (matrixCanvas.DataContext != null)
                            {

                                Item matrixCanvasItem = matrixCanvas.DataContext as Item;

                                foreach (Mapping mapping in _solution.Mapping)
                                {
                                    if (videoItem.Id == mapping.VideoSourceId && matrixCanvasItem.Id == mapping.VideoMatrixId)
                                    {
                                        string xaml = System.Windows.Markup.XamlWriter.Save(canvas);
                                        Canvas nCanvas = System.Windows.Markup.XamlReader.Parse(xaml) as Canvas;
                                        nCanvas.DataContext = videoItem;
                                        nCanvas.MouseRightButtonDown += videoCanvas_MouseRightButtonDown;
                                        // _ctlWrapPanelVideo.Children.Remove(canvas);
                                        matrixCanvas.Children.Add(nCanvas);

                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        void matrixCanvas_DragOver(object sender, DragEventArgs e)
        {
            if (!e.Data.GetDataPresent(typeof(Canvas)))
            {
                e.Effects = DragDropEffects.None;
                e.Handled = true;
            }
        }

        void matrixCanvas_Drop(object sender, DragEventArgs e)
        {
            IDataObject data = e.Data;

            if (data.GetDataPresent(typeof(Canvas)))
            {
                Canvas matrixCanvas = sender as Canvas;
                Canvas rect = data.GetData(typeof(Canvas)) as Canvas;
                if (matrixCanvas.Children.Count > 2 && matrixCanvas.Children[2] != null)
                {
                    matrixCanvas.Children.Remove(matrixCanvas.Children[2]);
                }
                string xaml = System.Windows.Markup.XamlWriter.Save(rect);
                Canvas nCanvas = System.Windows.Markup.XamlReader.Parse(xaml) as Canvas;
                nCanvas.DataContext = rect.DataContext as Item;
                nCanvas.MouseRightButtonDown += videoCanvas_MouseRightButtonDown;
                //this._ctlWrapPanelVideo.Children.Remove(rect);
                matrixCanvas.Children.Add(nCanvas);


                //发送视频切换指令
                Solution solution = new Solution();
                solution.Mapping = new List<Mapping>();
                Mapping mapping = new Mapping();
                mapping.VideoMatrixId = (matrixCanvas.DataContext as Item).Id;
                mapping.VideoSourceId = (rect.DataContext as Item).Id;
                solution.Mapping.Add(mapping);

                string targetIP = System.Configuration.ConfigurationManager.AppSettings["TargetIP"];
                string targetPort = System.Configuration.ConfigurationManager.AppSettings["TargetPort"];
                // 直接发送到视频切换设备
                Untils.VMUdpUntil.SendPointTarget(targetIP, targetPort, solution);
            }
        }

        void matrixRadioButton_Checked(object sender, RoutedEventArgs e)
        {
            RadioButton radioButton = sender as RadioButton;
            _checkedMatrixItem = radioButton.DataContext as Item;

        }

        /// <summary>
        /// 加载视频信息
        /// </summary>
        private void LoadVideoSource()
        {
            _listVideoSource = VMSolutionUntil.GetListVideoSource(VMSolutionUntil.GetVideoSourceFilePath(), "VideoSource");
            if (_listVideoSource != null)
            {
                _ctlWrapPanelVideo.Children.Clear();
                foreach (Item item in _listVideoSource)
                {
                    Canvas videoCanvas = new Canvas();
                    videoCanvas.PreviewMouseMove += videoCanvas_PreviewMouseMove;
                    videoCanvas.Height = 50;
                    videoCanvas.Width = 90;
                    videoCanvas.Margin = new Thickness(2);

                    Rectangle videoRectangle = new Rectangle();
                    videoRectangle.Width = 90;
                    videoRectangle.Height = 50;
                    videoRectangle.Fill = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFBAE4FF"));

                    videoCanvas.Children.Add(videoRectangle);
                    Label videoLabel = new Label();
                    videoLabel.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center;
                    videoLabel.VerticalContentAlignment = System.Windows.VerticalAlignment.Center;
                    videoLabel.Width = 90;
                    videoLabel.Height = 50;
                    videoLabel.Content = item.Caption;
                    videoCanvas.DataContext = item;
                    videoCanvas.Children.Add(videoLabel);


                    _ctlWrapPanelVideo.Children.Add(videoCanvas);
                }
            }
            else
            {
                _ctlWrapPanelVideo.Children.Clear();
            }
        }

        void videoCanvas_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            Canvas oCanvas = sender as Canvas;
            if (oCanvas != null && oCanvas.DataContext != null)
            {
                Item item = oCanvas.DataContext as Item;

                if (_ctlWrapPanelMatrix.Children != null)
                {

                    foreach (Canvas nCanvas in _ctlWrapPanelMatrix.Children)
                    {
                        if (nCanvas != null && nCanvas.DataContext != null)
                        {
                            Item matrixItem = nCanvas.DataContext as Item;
                            if (nCanvas.Children.Count > 2)
                            {
                                if (nCanvas.Children[2] != null)
                                {
                                    Canvas videoCanvas = nCanvas.Children[2] as Canvas;
                                    if (videoCanvas != null && videoCanvas.DataContext != null)
                                    {
                                        Item videoItem = videoCanvas.DataContext as Item;
                                        if (videoItem.Id == item.Id)
                                        {
                                            nCanvas.Children.Remove(videoCanvas);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        void videoCanvas_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                this.StartDrag(sender, e);
            }


        }


        private void StartDrag(object sender, MouseEventArgs e)
        {
            this._dragScope = sender as FrameworkElement;

            this._dragScope.AllowDrop = true;

            DragEventHandler draghandler = new DragEventHandler(DragScope_PreviewDragOver);
            this._dragScope.PreviewDragOver += draghandler;

            this._adorner = new DragAdorner(this._dragScope, (UIElement)sender as Canvas, 0.5);
            _dragScopeasVisual = sender as Canvas;
            this._layer = AdornerLayer.GetAdornerLayer(this._dragScopeasVisual);
            this._layer.Add(this._adorner);

            DataObject data = new DataObject(typeof(Canvas), sender as Canvas);
            DragDrop.DoDragDrop(sender as Canvas, data, DragDropEffects.Copy);

            AdornerLayer.GetAdornerLayer(this._dragScope).Remove(this._adorner);
            this._adorner = null;

            this._dragScope.PreviewDragOver -= draghandler;
        }

        void DragScope_PreviewDragOver(object sender, DragEventArgs args)
        {
            if (this._adorner != null)
            {
                this._adorner.LeftOffset = args.GetPosition(this._dragScope).X;
                this._adorner.TopOffset = args.GetPosition(this._dragScope).Y;
            }

        }

        private void _ctlzlight1on_Click_1(object sender, RoutedEventArgs e)
        {
            SendOperateToAgent("zlight1on");
        }

        private void _ctlzlight1hy_Click_1(object sender, RoutedEventArgs e)
        {
            SendOperateToAgent("zlight1hy");
        }

        private void _ctlzlight1hd_Click_1(object sender, RoutedEventArgs e)
        {
            SendOperateToAgent("zlight1hd");
        }

        private void _ctlzlight1zs_Click_1(object sender, RoutedEventArgs e)
        {
            SendOperateToAgent("zlight1zs");
        }

        private void _ctlzlight2on_Click_1(object sender, RoutedEventArgs e)
        {
            SendOperateToAgent("zlight2on");
        }

        private void _ctlzlight2m_Click_1(object sender, RoutedEventArgs e)
        {
            SendOperateToAgent("zlight2m");
        }

        private void _ctlzlight2a_Click_1(object sender, RoutedEventArgs e)
        {
            SendOperateToAgent("zlight2a");
        }

        private void _ctlzlight2off_Click_1(object sender, RoutedEventArgs e)
        {
            SendOperateToAgent("zlight2off");
        }

        private void _ctlzsoundon_Click_1(object sender, RoutedEventArgs e)
        {
            SendOperateToAgent("zsoundon");
        }

        private void _ctlzsoundoff_Click_1(object sender, RoutedEventArgs e)
        {
            SendOperateToAgent("zsoundoff");
        }

        private void _ctlzsoundupon_Click_1(object sender, RoutedEventArgs e)
        {
            SendOperateToAgent("zsoundupon");
        }

        private void _ctlzsoundupoff_Click_1(object sender, RoutedEventArgs e)
        {
            SendOperateToAgent("zsoundupoff");
        }

        private void _ctlzsounddownon_Click_1(object sender, RoutedEventArgs e)
        {
            SendOperateToAgent("zsounddownon");
        }

        private void _ctlzsounddownoff_Click_1(object sender, RoutedEventArgs e)
        {
            SendOperateToAgent("zsounddownoff");
        }

        private void _ctlzdrop1up_Click_1(object sender, RoutedEventArgs e)
        {
            SendOperateToAgent("zdrop1up");
        }

        private void _ctlzdrop1down_Click_1(object sender, RoutedEventArgs e)
        {
            SendOperateToAgent("zdrop1down");
        }

        private void _ctlzdrop1stop_Click_1(object sender, RoutedEventArgs e)
        {
            SendOperateToAgent("zdrop1stop");
        }

        private void _ctlzdrop2up_Click_1(object sender, RoutedEventArgs e)
        {
            SendOperateToAgent("zdrop2up");
        }

        private void _ctlzdrop2down_Click_1(object sender, RoutedEventArgs e)
        {
            SendOperateToAgent("zdrop2down");
        }

        private void _ctlzdrop2stop_Click_1(object sender, RoutedEventArgs e)
        {
            SendOperateToAgent("zdrop2stop");
        }

        /// <summary>
        /// 发送操作指令到Agent
        /// </summary>
        /// <param name="strOperate"></param>
        private void SendOperateToAgent(string strOperate)
        {
            string targetIP = System.Configuration.ConfigurationManager.AppSettings["TargetIP"];
            int targetPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TargetPort"]);
            // 发送到agent程序，让agent程序转发

             byte[] udpData = System.Text.Encoding.Default.GetBytes(strOperate);
           // Untils.VMAgentUtil.SendToAgent(targetIP, targetPort, strOperate);

             Untils.VMUdpUntil.SendUdpClient(targetIP, targetPort.ToString(), udpData, udpData.Length);
            //string targetIP = System.Configuration.ConfigurationManager.AppSettings["TargetIP"];
            //string targetPort = System.Configuration.ConfigurationManager.AppSettings["TargetPort"];
            //// 直接发送到视频切换设备
            //Untils.VMUdpUntil.SendPointTarget(targetIP, targetPort, strOperate);
        }

        private void _ctlguanshanon_Click_1(object sender, RoutedEventArgs e)
        {
            SendOperateToAgent("zwopen");
        }

        private void _ctlguanshanoff_Click_1(object sender, RoutedEventArgs e)
        {
            SendOperateToAgent("zwclose");
        }
    }
}
